/*	Copyright 2008 Jacquemin Valentin

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
	
	@author pollux
 */
package org.poxd.tools;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;

import org.apache.log4j.Logger;
import org.poxd.Sniwe;
import org.poxd.model.Language;
import org.poxd.persistance.LanguageDAO;

/**
 * @author pollux
 * 
 */
public class ConfigUtils {

	public static String FS = System.getProperty("file.separator");

	private static final String DB_DIRECTORY = Sniwe.USER_HOME + FS + "."
			+ Sniwe.APP_NAME + FS + "db";

	private static final Logger log = Logger.getLogger(ConfigUtils.class);

	public static final String JDBC_PATH = "jdbc:hsqldb:file:" + DB_DIRECTORY
			+ FS + Sniwe.APP_NAME;

	public static final String DB_USER = "sa";

	public static final String DB_PASSWORD = "";

	public static final String SNIWE_PROPERTIES_PATH = "/resources/Sniwe.properties";

	public static final String LANGUAGE = "language#";

	public static final String NAME = "name";

	public static final String LOGO = "logo";

	public static final String MARKER = "marker";

	/**
	 * Create the user directory
	 */
	public static void createUserDir() throws IOException {
		File userDir = new File(Sniwe.SNIWE_DIR);
		log.info("Create directory : " + Sniwe.SNIWE_DIR);
		if (!userDir.isDirectory()) {
			if (!createDir(Sniwe.SNIWE_DIR)) {
				// TODO refactoriser
				throw new IOException("Unable to create the SNIWE directory");
			}
		}
	}

	/**
	 * Init the database
	 */
	public static void initDB() throws ClassNotFoundException, IOException,
			SQLException {
		File dbDir = new File(DB_DIRECTORY);
		log.info("Create directory : " + DB_DIRECTORY);
		if (!dbDir.isDirectory()) {
			if (!createDir(DB_DIRECTORY)) {
				throw new IOException("Unable to create de db directory");
			}

			Class.forName("org.hsqldb.jdbcDriver");
			Connection connection = DriverManager.getConnection(JDBC_PATH,
					DB_USER, DB_PASSWORD);
			connection.setAutoCommit(false);
			Statement stmt = connection.createStatement();

			InputStream ddl = Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("resources/schema-export.sql");
			Scanner sql = new Scanner(ddl);
			log.debug("DB initialisation");
			while (sql.hasNextLine()) {
				String line = sql.nextLine();
				log.debug(line);
				stmt.addBatch(line);
			}
			try {
				stmt.executeBatch();
				connection.commit();
				stmt.execute("SHUTDOWN");
			} catch (SQLException e) {
				log.warn("DB initialisation FAILED");
				connection.rollback();
			}
//			initLanguages();
			log.debug("DB initialisation OK");
		}
	}

	private static void initLanguages() throws IOException {
		Properties props = new Properties();
		props
				.load(ConfigUtils.class
						.getResourceAsStream(SNIWE_PROPERTIES_PATH));

		String name;
		String logo;
		String marker;
		LanguageDAO languageDAO = new LanguageDAO();
		Language l = null;
		for (int i = 1;; i++) {
			try {
				name = props.get(LANGUAGE + i + "." + NAME).toString();
				logo = props.get(LANGUAGE + i + "." + LOGO).toString();
				marker = props.get(LANGUAGE + i + "." + MARKER).toString();
			} catch (NullPointerException e) {
				break;
			}
			if(name == null){
				break;
			}
			l = new Language(name, marker, new URLContent(logo));
			log.debug("Persisting language : " + l);
			languageDAO.addLanguage(l);
		}
	}

	private static boolean createDir(String dir) {
		File f = new File(dir);
		return f.mkdir();
	}
}
